package com.merlin.security.demo.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.merlin.security.demo.exception.UserNotExistException;
import com.merlin.security.demo.web.dto.User;

import lombok.extern.java.Log;


/**
 * 
 * @author Merlin
 *
 */
@RestController
@Log
public class UserController {
	
	
	
	@GetMapping("/queryOneUser")
	public List<User> queryOneUser(@RequestParam String username){
		log.info(username);
		return generateUsers();
	}
	
	
	@GetMapping("/queryAllUser")
	public List<User> queryAllUser(){
		return generateUsers();
	}
	
	
	@GetMapping("/queryPageUser")
    public List<User> queryPageUser(@PageableDefault(page = 1, size = 2, sort = "username") Pageable pageable) {
        System.out.println(pageable.getPageNumber());
        System.out.println(pageable.getPageSize());
        System.out.println(pageable.getSort());
        return generateUsers();
    }
	
	//URL添加了正则表达式，表示id只能是数字
	@GetMapping("/getInfo/{id:\\d+}")
	public User getInfo(@PathVariable String id) {
	    System.out.println("查询的对象ID为：".concat(id));
	    User user = new User();
	    user.setUsername("Merlin");
	    return user;
	}
	
	@PostMapping("/user4")
	public User idCardValidatorTest(@RequestBody @Valid User user, BindingResult bindingResult) {
	    if (bindingResult.hasErrors()) {
	        bindingResult.getAllErrors().forEach(error -> System.out.println(error.getDefaultMessage()));
	    }
	    user.setId(4);
	    return user;
	}
	
	@GetMapping("/userException/{id:\\d+}")
	@ResponseBody
	public User userException(@PathVariable Integer id) {
		throw new UserNotExistException(id);
	}
	
	
	private List<User> generateUsers() {
		List<User> users = new ArrayList<>();
		
		users.add(new User());
		users.add(new User());
		users.add(new User());
		
		return users;
	}

	
  
}
